package com.changer.common.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.changer.common.service.ImageCompressPolicy;
import com.changer.framework.util.FileUtils;
import com.changer.framework.util.IOUtils;
import com.changer.framework.util.ImageUtils;
import com.changer.framework.util.StringUtils;

/**
 * @author Jiwei Guo
 *
 */
public class DefaultImageCompressPolicy implements ImageCompressPolicy{
	
	private static final Logger LOGGER = LoggerFactory.getLogger(DefaultImageCompressPolicy.class);
	
	private String suffix;

	private int width;

	private int height;

	public File compress(File src) throws Exception{
		return compress(src, null);
	}
	
	public File compress(File src, String suffix) throws Exception {
		if(width == 0 || height == 0){
			throw new IllegalArgumentException("width or height can't be zero");
		}
		String name = rename(src, suffix);
		File compress = new File(src.getParent(), name);
		if(!compress.exists()){
			compress.createNewFile();
		}
		FileInputStream fis = new FileInputStream(src);
		BufferedImage bufferedImg = ImageIO.read(fis);
		int srcWidth = bufferedImg.getWidth();
		int srcHeight = bufferedImg.getHeight();
		String str = "original";
		String msg = " using " + str + " width and height";
		if(srcWidth < width && srcHeight < height){
			FileUtils.copyFile(src, compress);
		} else{
			str = "specified";
			ImageUtils.resize(src, width, height, compress);
		}
		LOGGER.debug("compressed size : " + FileUtils.toFileSizeUnit(compress.length()) + msg);
		return compress;
	}
	
	private String rename(File src, String suffix){
		String name = src.getName();
		name = StringUtils.getPrefix(name) + getConcatKey(suffix) + StringUtils.getSuffix(name);
		return name;
	}
	
	private String getConcatKey(String suffix){
		if(StringUtils.isEmpty(suffix)){
			return this.getSuffix().trim();
		}
		return suffix;
	}

	public String getSuffix() {
		return suffix;
	}

	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}
}
